import collections


class Solution(object):
    def sumOfDistancesInTree(self, n, edges):
        d_edges = collections.defaultdict(set)
        for u, v in edges:
            d_edges[u].add(v)
            d_edges[v].add(u)
        d_dist = {}
        d_count = {}
        ans = [0] * n

        def dfs(u):
            count = 0
            dist = 0
            for v in d_edges[u]:
                d_edges[v].remove(u)
                houxu_count, houxu_dist = dfs(v)
                count += houxu_count
                dist += houxu_dist
            d_dist[u] = dist + count
            d_count[u] = count + 1
            return d_count[u], d_dist[u]

        dfs(0)

        def dfs2(p, u):
            if p == -1:
                ans[u] = d_dist[u]
            else:
                ans[u] = ans[p] + n - 2 * d_count[u]
            for v in d_edges[u]:
                dfs2(u, v)

        dfs2(-1, 0)
        return ans


data = Solution()
n = 6
edges = [[0, 1], [0, 2], [2, 3], [2, 4], [2, 5]]
print(data.sumOfDistancesInTree(n, edges))
